<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="修改密码" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { updatePwd } from '@/api/sys/user';
  const emit = defineEmits(['success', 'register']);
  const resetForm: FormSchema[] = [
    {
      field: 'password',
      label: '旧密码',
      component: 'InputPassword',
      required: true,
    },
    {
      field: 'newPassword',
      label: '新密码',
      component: 'InputPassword',
      required: true,
    },
  ];
  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: resetForm,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      const { password, newPassword } = values;
      setModalProps({ confirmLoading: true });
      await updatePwd(password, newPassword);
      createMessage.success('修改成功');
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
